import grails.util.GrailsUtil

class JettystaticGrailsPlugin {
    def version = 0.2
    def dependsOn = [:]
    
    def author = "David Hernandez"
        def authorEmail = "dahernan@gmail.com"
        def title = "This plugin use jetty to server static content"
        def description = '''
    Plugin to server static content with jetty servlet in develoment and production, optional you can 
    configure with any other server in production
    '''
	

    def doWithWebDescriptor = { webXml ->
    	log.info "Jetty Static Initializing servlet"  
	    def dir = application.config?.jettystatic.dir
	    if(!dir){	    	
	    	dir = './static'
	    }
	    
	    def mapping = '/resources/*'
	    def env = GrailsUtil.environment
	    log.info "Jetty Static: environment '${env}'"
	    if(application.config?.jettystatic.ignore && env != "development"){
	    	log.info "Jetty Static: No jetty static servlet inicialized"
	    	return
	    }
	    
	    log.info "Jetty Static dir '${dir}' and mapping '${mapping}'"
	           
	    def servlets = webXml.'servlet'
		
		servlets[servlets.size()-1] + {
			'servlet' {
				 log.info 'Jetty Static generating <servlet> for static content'
				 
				'servlet-name'("jettystatic")
				'servlet-class'("org.mortbay.jetty.servlet.DefaultServlet")			
		
				'init-param' {
					'param-name'("resourceBase")
					'param-value'(dir)  
				}			
				
				'init-param' {
						'param-name'("dirAllowed")
						'param-value'("false")  
				}
				 
				'init-param' {
					'param-name'("gzip")
					'param-value'("true")  
				}
		
				'load-on-startup'("1")
			}			
		}
		
	    def mappings = webXml.'servlet-mapping'
	    mappings[mappings.size()-1] + {
			'servlet-mapping' {
				'servlet-name'("jettystatic")
				'url-pattern'(mapping)
			}
		}
    }
    
	                                      
 
}
